package com.dms.modules.user.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dms.common.api.ApiResponse;
import com.dms.common.security.SecurityUtils;
import com.dms.modules.user.entity.UserBrowseHistory;
import com.dms.modules.user.service.UserBrowseHistoryService;
import com.dms.modules.user.vo.UserBrowseHistoryVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import java.beans.PropertyEditorSupport;

@Slf4j
@RestController
@RequestMapping("/api/v1/user/browse-history")
@Api(tags = "用户浏览历史接口")
@Validated
@PreAuthorize("hasRole('USER')")
public class UserBrowseHistoryController {

    @Autowired
    private UserBrowseHistoryService browseHistoryService;

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(Long.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) {
                if (text == null || text.isEmpty() || "undefined".equals(text)) {
                    setValue(null);
                } else {
                    setValue(Long.valueOf(text));
                }
            }
        });
    }

    @PostMapping("/{productId}")
    @ApiOperation("添加浏览历史")
    @PreAuthorize("isAuthenticated()")
    public ApiResponse<Boolean> addBrowseHistory(
            @PathVariable @NotNull(message = "商品ID不能为空") Long productId,
            @RequestParam(required = false) Long categoryId,
            @RequestParam(required = false) Integer stayDuration) {
        Long userId = SecurityUtils.getCurrentUserId();
        return ApiResponse.success(browseHistoryService.addBrowseHistory(userId, productId, categoryId, stayDuration));
    }

    @DeleteMapping("/{productId}")
    @ApiOperation("删除浏览历史")
    @PreAuthorize("isAuthenticated()")
    public ApiResponse<Boolean> deleteBrowseHistory(
            @PathVariable @NotNull(message = "商品ID不能为空") Long productId) {
        Long userId = SecurityUtils.getCurrentUserId();
        return ApiResponse.success(browseHistoryService.deleteProductBrowseHistory(userId, productId));
    }

    @DeleteMapping("/clear")
    @ApiOperation("清空浏览历史")
    @PreAuthorize("isAuthenticated()")
    public ApiResponse<Boolean> clearBrowseHistory() {
        Long userId = SecurityUtils.getCurrentUserId();
        return ApiResponse.success(browseHistoryService.clearBrowseHistory(userId));
    }

    @GetMapping("/list")
    @ApiOperation("获取浏览历史列表")
    @PreAuthorize("isAuthenticated()")
    public ApiResponse<IPage<UserBrowseHistoryVO>> getBrowseHistory(
            @RequestParam(defaultValue = "1") @Min(value = 1, message = "页码不能小于1") Integer pageNum,
            @RequestParam(defaultValue = "10") @Min(value = 1, message = "每页条数不能小于1") Integer pageSize,
            @RequestParam(required = false) Long categoryId) {
        Long userId = SecurityUtils.getCurrentUserId();
        Page<UserBrowseHistory> page = new Page<>(pageNum, pageSize);
        return ApiResponse.success(browseHistoryService.listWithProductInfo(page, userId, categoryId));
    }
} 